import { ref } from 'vue'

// loading
let loading = ref<boolean>(false)

// 分页
let total = ref<number>()
let offset: number = 0
let limit: number = 10
let paginate = ref({ offset, limit })

// 多选
export type SelectedRowKeys = string[] | number[]
const selectedRowKeys = ref<SelectedRowKeys>([])
const emptySelectedRowKeys = () => (selectedRowKeys.value = [])

// 设置请求 api
let requestApi: Function
const setRequestApi = (api: Function) => {
  requestApi = api
}

// 设置请求参数
type SearchParamsType = Record<string, string | number | boolean | string[]>
let searchParams: SearchParamsType = {}

// 请求参数处理，返回非空属性
type BlacklistType = (string | undefined | null)[]
const blacklist: BlacklistType = ['', undefined, null]

const searchParamsFormatter = (params: any) => {
  let _params: SearchParamsType = {}
  for (let key in params) {
    if (blacklist.includes(params[key])) continue
    _params[key] = params[key]
  }
  return _params
}
const setSearchParams = (params: SearchParamsType) => {
  searchParams = { ...searchParamsFormatter(params), ...paginate.value }
}

// table
let tableData = ref([])
const getTableData = () => {
  tableData.value = []
  setSearchParams(searchParams)
  // console.log('api: ', requestApi)
  console.log('searchParams:', searchParams)
  loading.value = true
  requestApi(searchParams)
    .then((res: any) => {
      console.log('~~~~~ table ~~~~~:', res)
      const { list, total: _total } = res
      tableData.value = list
      total.value = _total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

const resetPaginate = () => {
  paginate.value.offset = offset
  // paginate.value.limit = limit
}

const resetUseTableState = () => {
  selectedRowKeys.value = []
  resetPaginate()
}

export {
  loading,
  total,
  paginate,
  requestApi,
  tableData,
  setRequestApi,
  setSearchParams,
  selectedRowKeys,
  getTableData,
  resetPaginate,
  emptySelectedRowKeys,
  resetUseTableState
}
